package com.yctan;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileNio {
    public static void main(String[] args) {
        RandomAccessFile aFile = null;
        RandomAccessFile aFile1 = null;
        try {
            aFile = new RandomAccessFile("C:\\Users\\yctan-pc\\Desktop\\新建 文本文档.txt", "rw");
            FileChannel fileChannel = aFile.getChannel();
            File file = new File("C:\\Users\\yctan-pc\\Desktop\\新建 文本文档3.txt");
            file.createNewFile();
            aFile1  = new RandomAccessFile(file, "rw");
            FileChannel fileChannel1 = aFile1.getChannel();
            fileChannel.transferTo(0,fileChannel.size(),fileChannel1);
            System.out.println(Thread.currentThread().getName()+fileChannel.position());
            byte[] bytes = new byte[1024];
            ByteBuffer buf = ByteBuffer.allocate(Integer.parseInt(String.valueOf(fileChannel.size())));
            System.out.println(Thread.currentThread().getName()+"开始位置：" + buf.position());
            int bytesRead = fileChannel1.write(buf);
            System.out.println(Thread.currentThread().getName()+"开始位置：" + buf.position());
            while (bytesRead != -1) {
                System.out.println(Thread.currentThread().getName()+"开始位置：" + buf.position());
                buf.flip();
                System.out.println(Thread.currentThread().getName()+"开始位置：" + buf.position());
                while (buf.hasRemaining()) {
                    System.out.println(Thread.currentThread().getName()+"--------------------" + buf.remaining() + "-----------------------");
                    if (buf.remaining() < 1024) {
                        if (buf.remaining() == 0) {
                            continue;
                        }
                        bytes = new byte[buf.remaining()];
                    }
                    buf.get(bytes);
                    System.out.println(Thread.currentThread().getName()+new String(bytes, "utf-8"));
                }
                buf.compact();
                bytesRead = fileChannel.read(buf);
            }
            fileChannel.write(buf);
            //System.out.println(Thread.currentThread().getName()+stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (aFile != null) {
                    aFile.close();
                }
                if (aFile1 != null) {
                    aFile1.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
